<template>
  <div class="donation-container">
    <div class="banner" style="background-image: url('/src/assets/background/bg3.jpg')">
      <h1 class="page-title">爱心捐赠</h1>
      <p class="page-subtitle">用爱心温暖每一个生命</p>
    </div>

    <div class="content">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-card class="filter-card">
          <div class="filter-content">
            <div class="filter-title">项目筛选</div>
            <div class="filter-options">
              <el-radio-group v-model="filterStatus" @change="handleStatusChange">
                <el-radio-button label="">全部</el-radio-button>
                <el-radio-button label="active">进行中</el-radio-button>
                <el-radio-button label="completed">已完成</el-radio-button>
                <el-radio-button label="closed">已关闭</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 项目列表 -->
      <div class="projects-section">
        <div class="project-grid">
          <el-card v-for="project in projects" :key="project.id" class="project-card" shadow="hover">
            <div class="project-header">
              <h3 class="project-name">{{ project.project_name }}</h3>
              <el-tag :type="getStatusType(project.status)">
                {{ getStatusText(project.status) }}
              </el-tag>
            </div>
            
            <div class="project-progress">
              <el-progress 
                :percentage="Math.round((project.current_amount / project.target_amount) * 100)"
                :color="getProgressColor"
                :show-text="false"
                :stroke-width="10"
                :text-inside="true"
              />
              <div class="progress-info">
                <span>已筹：¥{{ project.current_amount.toFixed(2) }}</span>
                <span>目标：¥{{ project.target_amount.toFixed(2) }}</span>
              </div>
            </div>

            <div class="project-stats">
              <div class="stat-item">
                <el-icon><User /></el-icon>
                <span>{{ project.donor_count }}人参与</span>
              </div>
              <div class="stat-item">
                <el-icon><Calendar /></el-icon>
                <span>截止日期：{{ formatDate(project.end_date) }}</span>
              </div>
            </div>

            <div class="project-actions">
              <el-button 
                type="primary" 
                class="donate-btn" 
                :disabled="project.status !== 'active'"
                @click="handleDonate(project)"
              >
                立即捐款
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[6, 12, 18]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 捐款对话框 -->
    <el-dialog
      v-model="donateDialogVisible"
      title="爱心捐款"
      width="30%"
      :before-close="handleDialogClose"
      class="donate-dialog"
    >
      <el-form
        ref="donateFormRef"
        :model="donateForm"
        :rules="donateRules"
        label-width="100px"
      >
        <el-form-item label="捐款金额" prop="amount">
          <el-input-number 
            v-model="donateForm.amount" 
            :min="1" 
            :max="100000"
            :precision="2"
            :step="10"
            class="full-width"
          />
        </el-form-item>
        <el-form-item label="捐款人姓名" prop="donorName">
          <el-input v-model="donateForm.donorName" placeholder="请输入您的姓名" />
        </el-form-item>
        <el-form-item label="留言" prop="message">
          <el-input
            v-model="donateForm.message"
            type="textarea"
            :rows="3"
            placeholder="写下您的祝福语（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitDonation">确认捐款</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Calendar } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 状态
const projects = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(6)
const filterStatus = ref('')
const dateRange = ref([])

// 捐款表单
const donateDialogVisible = ref(false)
const donateFormRef = ref(null)
const donateForm = ref({
  projectId: null,
  userId: JSON.parse(localStorage.getItem('userInfo')).id,
  amount: 100,
  donorName: '',
  message: ''
})

// 表单验证规则
const donateRules = {
  amount: [
    { required: true, message: '请输入捐款金额', trigger: 'blur' },
    { type: 'number', min: 1, message: '捐款金额必须大于0', trigger: 'blur' }
  ],
  donorName: [
    { required: true, message: '请输入捐款人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
  ]
}

// 获取项目列表
const getProjects = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      status: filterStatus.value
    }
    if (dateRange.value && dateRange.value.length === 2) {
      params.dateRange = dateRange.value
    }

    const res = await request.get('/donation/list', { params })
    projects.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  }
}

// 处理捐款
const handleDonate = (project) => {
  donateForm.value.projectId = project.id
  donateDialogVisible.value = true
}

// 提交捐款
const submitDonation = async () => {
  if (!donateFormRef.value) return

  await donateFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await request.post('/donation/contribute', donateForm.value)
        ElMessage.success('捐款成功，感谢您的爱心！')
        handleDialogClose()
        getProjects() // 刷新项目列表
      } catch (error) {
        console.error('捐款失败:', error)
        ElMessage.error('捐款失败，请稍后重试')
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  donateDialogVisible.value = false
  if (donateFormRef.value) {
    donateFormRef.value.resetFields()
  }
  donateForm.value = {
    projectId: null,
    userId: JSON.parse(localStorage.getItem('userInfo')).id,
    amount: 100,
    donorName: '',
    message: ''
  }
}

// 状态处理
const getStatusType = (status) => {
  const types = {
    active: 'success',
    completed: 'info',
    closed: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    active: '进行中',
    completed: '已完成',
    closed: '已关闭'
  }
  return texts[status] || status
}

// 进度条颜色
const getProgressColor = computed(() => {
  return (percentage) => {
    if (percentage < 30) return '#909399'
    if (percentage < 70) return '#e6a23c'
    return '#67c23a'
  }
})

// 日期格式化
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 事件处理
const handleStatusChange = () => {
  currentPage.value = 1
  getProjects()
}

const handleDateChange = () => {
  currentPage.value = 1
  getProjects()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  getProjects()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  getProjects()
}

onMounted(() => {
  getProjects()
})
</script>

<style scoped lang="scss">
.donation-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  overflow-x: hidden;
}

.banner {
  background-size: cover;
  background-position: center;
  padding: 220px 20px;
  text-align: center;
  color: white;
  position: relative;
  transition: all 0.6s ease;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.4);
    z-index: 1;
    transition: background 0.4s ease;
  }

  &:hover::before {
    background: rgba(0, 0, 0, 0.3);
  }

  .page-title {
    font-size: 48px;
    margin-bottom: 24px;
    font-weight: 800;
    position: relative;
    z-index: 2;
    text-shadow: 2px 2px 6px rgba(0,0,0,0.4);
    letter-spacing: 3px;
    transform: translateY(-20px);
    opacity: 0;
    animation: fadeInDown 1s ease forwards;
  }

  .page-subtitle {
    font-size: 22px;
    opacity: 0;
    position: relative;
    z-index: 2;
    text-shadow: 1px 1px 4px rgba(0,0,0,0.3);
    letter-spacing: 2px;
    transform: translateY(20px);
    animation: fadeInUp 1s ease 0.3s forwards;
  }
}

@keyframes fadeInDown {
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fadeInUp {
  to {
    transform: translateY(0);
    opacity: 0.95;
  }
}

.content {
  max-width: 1280px;
  margin: -100px auto 60px;
  padding: 0 30px;
  position: relative;
  z-index: 1;
}

.filter-section {
  margin-bottom: 40px;
}

.filter-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 6px 20px rgba(0,0,0,0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 24px rgba(0,0,0,0.12);
  }
}

.filter-content {
  padding: 25px;
}

.filter-title {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 24px;
  position: relative;
  padding-left: 15px;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 20px;
    background: var(--el-color-primary);
    border-radius: 2px;
  }
}

.filter-options {
  display: flex;
  gap: 24px;
  align-items: center;
}

.project-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 35px;
  margin-bottom: 50px;
}

.project-card {
  border-radius: 20px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;

  &:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 28px rgba(0,0,0,0.15);
  }
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.project-name {
  font-size: 22px;
  color: #303133;
  margin: 0;
  font-weight: 700;
  line-height: 1.4;
}

.project-progress {
  margin-bottom: 24px;

  .el-progress-bar__outer {
    border-radius: 8px;
  }

  .el-progress-bar__inner {
    border-radius: 8px;
    transition: all 0.6s ease;
  }
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  color: #606266;
  font-size: 15px;
  font-weight: 500;
}

.project-stats {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  color: #606266;
  font-size: 15px;
  padding: 15px 0;
  border-top: 1px dashed #ebeef5;
  border-bottom: 1px dashed #ebeef5;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-icon {
    font-size: 18px;
    color: var(--el-color-primary);
  }
}

.project-actions {
  display: flex;
  justify-content: center;
  padding-top: 10px;
}

.donate-btn {
  width: 100%;
  padding: 14px 0;
  font-size: 17px;
  font-weight: 600;
  letter-spacing: 2px;
  border-radius: 12px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);

  &:not(:disabled):hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(64,158,255,0.35);
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 50px;

  :deep(.el-pagination) {
    padding: 20px 30px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  }
}

.donate-dialog {
  :deep(.el-dialog) {
    border-radius: 20px;
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    padding: 25px;
    margin: 0;
    background: var(--el-color-primary);
    color: white;
  }

  :deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
    font-size: 20px;
  }

  :deep(.el-dialog__body) {
    padding: 30px 25px;
  }

  :deep(.el-dialog__footer) {
    padding: 20px 25px;
    border-top: 1px solid #ebeef5;
  }
}

.full-width {
  width: 100%;
}

@media (max-width: 768px) {
  .content {
    margin-top: -70px;
    padding: 0 15px;
  }

  .banner {
    padding: 180px 15px;

    .page-title {
      font-size: 36px;
    }

    .page-subtitle {
      font-size: 18px;
    }
  }

  .filter-options {
    flex-direction: column;
    align-items: stretch;
  }

  .project-grid {
    grid-template-columns: 1fr;
    gap: 25px;
  }

  .filter-card {
    border-radius: 16px;
  }

  .project-card {
    border-radius: 16px;
  }

  .donate-dialog {
    :deep(.el-dialog) {
      width: 90% !important;
      margin: 0 auto;
    }
  }
}
</style> 